import React, { Component } from 'react';
import { Tag , Input, Image, } from 'antd';
import Http from '../../util/http';
import Wheaders from '../../components/Headers';
import './index.less';

class Searchfict extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchResult: [],
            resultLength: 0,
        }
    }

    render() {
        const { searchResult, resultLength } = this.state;
        return (
            <div className={'searchfict'}>
                <Wheaders left={'返回'} middle={'搜索'} right={'首页'} />
                <div className={'search-header'}>
                    <Input placeholder='请输入小说名称' onChange={(e) => {this.onSearch(e.target.value)}}/>
                </div>
                {resultLength ? <div className={'search-result'}>
                    共找到{resultLength}部作品
                </div> : ''}
                <div className={'recommend'}>
                    {searchResult.map( (subItem, subIndex) => {
                        return (<div key={subIndex} className={'recommend-body'}>
                            <div className={'content'} onClick={this.Jump.bind(this, subItem.novelId)}>
                                <div className={'content-header'}>
                                    <Image className={'ant-img'} src={subItem.coverUrl} preview={false}  fallback={'http://image.hanlingsha.love/lwa/novel/lwa-default-novel-cover.jpeg'} />
                                </div>
                                <div className={'content-body'}>
                                    <h2 className={'title'} dangerouslySetInnerHTML={{__html: subItem.novelName}}></h2>
                                    <p className={'classify'}>
                                        <Tag className={'tag'}>{subItem.tagName}</Tag>
                                    </p>
                                </div>
                            </div>
                        </div>)
                    })}
                </div>
            </div>
        );
    }

    componentDidMount() {

    }

    Jump(id) {
        this.props.history.push({pathname: '/details' , state:{
            novelId: id,
        }});
    }

    onSearch(e) {
        if (! e) {
            this.setState({ searchResult: [], resultLength: 0});
            return;
        }
        Http.get('/Novel/searchNovel', { search: e}).then( res => {
            let searchResult = [];
            res.resultData.forEach( (item, index) => {
                item.novelName = item.novelName.replace(e, `<span style="color:red">${e}</span>`)
                searchResult.push(item);
            });
            this.setState({ searchResult, resultLength: searchResult.length});
        });
    }
}

export default Searchfict;
